#pragma once
#include <unordered_map>
#include <string>
#include <iostream>
#include <fstream>
#include "Log.hpp"

const std::string esp = ": ";
const std::string default_path = "./dictionary.txt";
const std::string default_ret = "未知单词";

using namespace LogModule;

class Dictionary
{
public:
    bool Load(const std::string& path = default_path)
    {
        std::ifstream dict_file(path);
        if(!dict_file.is_open())
        {
            LOG(LogLevel::ERROR) << "未能打开字典文件! ";
            return false;
        }
        std::string pair;
        while(std::getline(dict_file, pair))
        {
            auto pos = pair.find(esp);
            if(pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "无法解析的对应关系[" << pair << "]";
                continue;
            }
            std::string english = pair.substr(0, pos);
            std::string chinese = pair.substr(pos + esp.size());
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "对应关系[" << pair << "]不完整";
                continue;
            }
            _dict[english] = chinese;
        }
        return true;
    }

    std::string Check(const std::string& word)
    {
        if(_dict.count(word))
            return _dict[word];
        else
            return default_ret;
    }
private:
    std::unordered_map<std::string, std::string> _dict;
};